package leecode

import "math"

func isBalanced(root *TreeNode) bool {
	return getHeight(root) != -1
}

func getHeight(node *TreeNode) int {
	if node == nil {
		return 0
	}
	leftHeight := getHeight(node.Left)
	if leftHeight == -1 {
		return -1
	}
	rightHeight := getHeight(node.Right)
	if rightHeight == -1 {
		return -1
	}
	result := math.Abs(float64(rightHeight - leftHeight))
	if result > 1 {
		return -1
	} else {
		result = 1 + math.Max(float64(leftHeight), float64(rightHeight))
	}
	return int(result)
}
